//
//  FindEmoticon.swift
//  EmotiDemo
//
//  Created by leador on 17/5/18.
//  Copyright © 2017年 袁满. All rights reserved.
//

import UIKit

class FindEmoticon: NSObject {

    static let shareInstance : FindEmoticon = FindEmoticon()
    
    lazy var manager : EmoticonManager = EmoticonManager()
    
    func findEmmticon(status:String?, font:UIFont)->NSMutableAttributedString? {
        
        guard let status = status else {
            return nil
        }
        
        let pattern = "\\[.*?\\]"
        
        guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
            return nil
        }
        
        let results = regex.matches(in: status, options: [], range: NSRange(location: 0, length: status.characters.count))
        
        let attmutableStr = NSMutableAttributedString(string: status)
        
        if results.count > 0 {
            
            for i in (0...(results.count-1)).reversed() {
                
                let result = results[i]
                
                let chs = (status as NSString).substring(with: result.range)
                
                guard let imagePath = findImagePath(chs: chs) else {
                    return nil
                }
                
                let attachment = EmoticonAttachment()
                attachment.image = UIImage(contentsOfFile: imagePath)
                attachment.bounds = CGRect(x: 0, y: -4, width: font.lineHeight, height: font.lineHeight)
                let attibuteAttachment = NSAttributedString(attachment: attachment)
                
                attmutableStr.replaceCharacters(in: result.range, with: attibuteAttachment)
            }
            
        }
        
        return attmutableStr
        
    }
    
    private func findImagePath(chs:String) -> String? {
        
        for package in manager.packages {
            
            for emoticon in package.emoticons {
                
                if emoticon.chs == chs {
                    return emoticon.pngPath
                }
                
            }
            
        }
        
        return nil
        
    }
    
}
